package cn.bluethink.timescaledb.util;

import onegis.dict.LogicalEnum;
import onegis.dict.SpatialEnum;
import onegis.dict.TemporalEnum;
import onegis.filter.GFilter;
import org.apache.commons.lang.StringUtils;
import org.geotools.filter.text.cql2.CQLException;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

public class FilterUtil {

    public static GFilter formatFilter(GFilter filter) {
        if (!StringUtils.isEmpty(filter.getBbox())) {
            filter.setSpatialOperator(SpatialEnum.bbox);
            filter.setGeom("geom");
        }
        Date startTime = filter.getStartTime();
        Date endTime = filter.getEndTime();
        if (startTime != null && endTime != null) {
            filter.setTemporalOperator(TemporalEnum.during);
        } else if (startTime != null) {
            filter.setTemporalOperator(TemporalEnum.after);
        } else if (endTime != null) {
            filter.setTemporalOperator(TemporalEnum.before);
        }
        return filter;
    }

    public static Filter getMergeFilter(List<GFilter> filters, FilterFactory2 filterFactory) throws CQLException {
        if (!CollectionUtils.isEmpty(filters)) {
            GFilter gFilter = filters.get(0);
            Filter filter = gFilter.createFilter();
            if (gFilter.getLogicalEnum() != null && 1 < filters.size()) {
                filters.remove(0);
                switch (gFilter.getLogicalEnum().getValue()) {
                    case 0:
                        return filterFactory.and(filter, getMergeFilter(filters,filterFactory));
                    case 1:
                        return filterFactory.or(filter, getMergeFilter(filters,filterFactory));
                    default:
                        return Filter.EXCLUDE;
                }
            }
            if (1 == filters.size()) {
                if (gFilter.getLogicalEnum() != null && gFilter.getLogicalEnum() == LogicalEnum.Not) {
                    return filterFactory.not(filter);
                }
                return filter;
            }
        }

        return Filter.EXCLUDE;
    }

}
